package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.utils.DateUtils;
import entity.PageResult;
import entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import java.util.Set;

/**
 * @Description:
 * @Author: yp
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private MenuDao menuDao;

    /**
     * 根据用户名查询
     *
     * @param username
     * @return
     */
    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        //取出userId, 查询出角色
        if (user != null) {
            Set<Role> roles = roleDao.findByUid(user.getId());
            //遍历
            if (roles != null && roles.size() > 0) {
                for (Role role : roles) {
                    //取出roleid, 查询权限
                    Set<Permission> permissions = permissionDao.findByRoleId(role.getId());
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }
        return user;
    }


   /* private List findByRoleId(Integer id) {
        List list2 = new ArrayList();
        LinkedHashSet<Menu>  menus = menuDao.findByRoleId(id);
        for (Menu menu : menus) {
            Map<String, Object> map = new HashMap();
            // TODO 区分菜单级别
            // level区分级别
            map.put("path", menu.getPath());
            map.put("title", menu.getName());
            map.put("icon", menu.getIcon());
            LinkedHashSet<Menu> menus2 = menuDao.findByPid(menu.getId());
            List list = new ArrayList();
            if (menus2 != null && menus2.size() > 0) {
                for (Menu menu1 : menus2) {
                    Map<String, Object> children = new HashMap<>();
                    children.put("path", menu1.getPath());
                    children.put("title", menu1.getName());
                    children.put("linkUrl", menu1.getLinkUrl());
                    list.add(children);
                }
            }
            map.put("children", list);
            list2.add(map);
        }
       return list2;
    }

    @Override
    public List getUserRole(String username) {
        User user = userDao.findByUsername(username);
        if(user==null){
            return null;
        }
        List list=new ArrayList();
        Set<Role> roles = roleDao.findByUid(user.getId());
        for (Role role : roles) {
            list.add(role);
        }
        return list;
    }*/

/*    @Override
    public List changeUserRole(int id) {
        //List list2 = new ArrayList();
        //TODO 正常是单一角色操作的菜单
        //TODO 角色ID
        List list2 =findByRoleId(id);
        return list2;
    }*/

    @Override
    public List changeUserName(String username, int id)  {
        User user = userDao.findByUsername(username);
        if(user==null){
            return null;
        }
        List list=new ArrayList();
        Set<Role> roles = roleDao.findByUid(user.getId());
        for (Role role : roles) {
            if(role.getId()!=id){
                list.add(role);
            }
        }
        return list;
    }
    /**
     * 新增套餐
     *
     * @param user
     * @param roleIds
     */
    @Override
    public void add(User user, Integer[] roleIds) {

        //向t_user插入一条记录
        userDao.add(user);
        // 向t_user_role插入多条记录
        Integer userId = user.getId();
        setUserAndRoleMidTable(userId, roleIds);
    }

    /**
     * 查询所有的套餐
     *
     * @return
     */
/*    @Override
    public List<Setmeal> getSetmeal() {
        return userDao.getSetmeal();
    }*/

    /**
     * 套餐详情(1.先直接查询套餐的基本信息 2.关联查询出检查组的信息List 3.关联查询出检查项的信息List)
     *
     * @param
     * @param
     * @return
     */
/*    @Override
    public Setmeal findById(Integer id, Integer type) {
        Setmeal setmeal = setMealDao.findById(id);

        if(type == 1){
            //不懒(使用一下)
            List<CheckGroup> checkGroups = setmeal.getCheckGroups();
            System.out.println(checkGroups.size());
            for (CheckGroup checkGroup : checkGroups) {
                List<CheckItem> checkItems = checkGroup.getCheckItems();
                System.out.println(checkItems.size());
            }
        }

        System.out.println(setmeal);
        //取出setmeal的id, 调用userDao 查询出List<CheckGroup> list 封装
        //遍历List<CheckGroup> list, 取出每一个CheckGroup的id, 调用CheckItemDao 查出 List<CheckItem> checkItems;
        return setmeal;
    }*/

/*    @Override
    public List<Map<String, Object>> getSetmealReport() {
        return setMealDao.getSetmealReport();
    }*/
    private void setUserAndRoleMidTable(Integer userId, Integer[] roleIds) {
        if (roleIds != null) {
            for (Integer roleId : roleIds) {
                Map map = new HashMap();
                map.put("userId", userId);
                map.put("roleId", roleId);
                userDao.setUserAndRoleMidTable(map);
            }
        }
    }

    /**
     * 分页条件查询
     *
     * @param queryPageBean 封装的查询条件
     * @return 分页结果封装对象
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) throws Exception {

        //调用Mybatis分页插件方法(自动帮我们做分页)
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());

        //调用Dao, 获得Page对象(page对象是分页插件自带的, 包含List, total...)
        Page<User> page = userDao.findPage(queryPageBean.getQueryString());


        List<User> result = page.getResult();
        for ( User user : result) {
            Date date = user.getBirthday();
            String dateStr = DateUtils.parseDate2String(date);
            Date orderDate = DateUtils.parseString2Date(dateStr);
            user.setBirthday(orderDate);
        }

        return new PageResult(page.getTotal(),result);
    }

    /**
     * 根据用户id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public User findById(int id) {

        return userDao.findById(id);
    }

    /**
     * 更新用户
     *
     * @param user
     * @param roleIds
     */
    @Override
    public void edit(User user, Integer[] roleIds) {
        //1.调用dao 更新User
        userDao.edit(user);
        //2.调用dao 通过id删除User关联的中间表(t_user_role)
        userDao.deleteAssociation(user.getId());
        //3.调用dao 把更新提交过来的roleIds 再进行关联
        setUserAndRoleMidTable(user.getId(), roleIds);
    }

    /**
     * 根据id删除用户
     *
     * @param id
     */
    @Override
    public void delete(Integer id) {

        //通过id删除User关联的中间表(t_user_role)
        userDao.deleteAssociation(id);

        //通过id删除user
        userDao.deleteById(id);
    }

    /**
     * 修改密码
     *
     * @param user
     */
    @Override
    public void editPassword(User user) {
        userDao.editPassword(user);
    }
    /**
     * 先给个固定的角色ID  后面换成动态ID
     *
     * @param username
     * @return
     */
    @Override
    public List findByUsername2(String username) {
        //TODO 正常是单一角色操作的菜单
        //TODO 角色ID
        User user = userDao.findByUsername(username);
        Set<Role> roles = roleDao.findByUid(user.getId());
        List<Integer> list3 = new ArrayList();
        for (Role role : roles) {
            list3.add(role.getId());
        }
        List list2 = findByRoleId(list3.get(0));
        return list2;
    }

    private List findByRoleId(Integer id) {
        List list2 = new ArrayList();
        LinkedHashSet<Menu>  menus = menuDao.findByRoleId(id);
        for (Menu menu : menus) {
            Map<String, Object> map = new HashMap();
            // TODO 区分菜单级别
            // level区分级别
            map.put("path", menu.getPath());
            map.put("title", menu.getName());
            map.put("icon", menu.getIcon());
            LinkedHashSet<Menu> menus2 = menuDao.findByPid(menu.getId());
            List list = new ArrayList();
            if (menus2 != null && menus2.size() > 0) {
                for (Menu menu1 : menus2) {
                    Map<String, Object> children = new HashMap<>();
                    children.put("path", menu1.getPath());
                    children.put("title", menu1.getName());
                    children.put("linkUrl", menu1.getLinkUrl());
                    list.add(children);
                }
            }
            map.put("children", list);
            list2.add(map);
        }
        return list2;
    }

    @Override
    public List getUserRole(String username) {
        User user = userDao.findByUsername(username);
        if(user==null){
            return null;
        }
        List list=new ArrayList();
        Set<Role> roles = roleDao.findByUid(user.getId());
        for (Role role : roles) {
            list.add(role);
        }
        return list;
    }

    @Override
    public List changeUserRole(int id) {
        //List list2 = new ArrayList();
        //TODO 正常是单一角色操作的菜单
        //TODO 角色ID
        List list2 =findByRoleId(id);
        return list2;
    }
    /**
     * 将头像图片名称存入数据库
     *
     * @param filename
     */
    @Override
    public void updateUserImgByFilename(String filename,String username) {
        User user = new User();
        user.setUsername(username);
        user.setUserImg(filename);
        userDao.updateUserImgByFilename(user);
    }

}
